package com.dz.lm.service.comp.account.impl;

import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.MD5Util;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.dao.compaccount.read.CompAccountDao;
import com.dz.lm.domain.compaccount.CompAccount;
import com.dz.lm.domain.compaccount.CompAccountExample;
import com.dz.lm.service.comp.account.CompAccountService;
import com.smartlbs.util.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.rowset.serial.SerialException;
import java.util.List;

@Service
public class CompAccountServiceImpl implements CompAccountService {
    @Resource(name = "readCompAccountDao")
    private CompAccountDao readCompAccountDao;
    @Resource(name = "writeCompAccountDao")
    private com.dz.lm.dao.compaccount.write.CompAccountDao writeCompAccountDao;
    @Override
    public int add(int compId, int userId, int type, String userName, String password) throws SerialException {
        CompAccount account = new CompAccount();
        account.setCompId(compId);
        account.setUserId(userId);
        account.setType(type);
        account.setUserName(userName);
        try {
            account.setPassword(MD5Util.MD5(password));
            account.setCeateTime(DateUtil.getNowDateTimeString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return writeCompAccountDao.insertSelective(account);
    }

    @Override
    public CompAccount get(String uName, String password) throws ServiceException {
        CompAccount account = null;
        CompAccountExample ex = new CompAccountExample();
        CompAccountExample.Criteria cr = ex.createCriteria();
        cr.andUserNameEqualTo(uName);
        try {
            if(!StringUtil.containEmpty(password)){
                cr.andPasswordEqualTo(MD5Util.MD5(password));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<CompAccount> accounts = readCompAccountDao.selectByExample(ex);
        if(accounts != null && accounts.size() >0){
            account = accounts.get(0);
        }
        return account;
    }

    @Override
    public int checking(String userName) throws ServiceException {
        int ret = 0;
        CompAccountExample ex = new CompAccountExample();
        CompAccountExample.Criteria cr = ex.createCriteria();
        cr.andUserNameEqualTo(userName);
        List<CompAccount> list = readCompAccountDao.selectByExample(ex);
        if(list != null && list.size() > 0 ){
            ret =1;
        }
        return ret;
    }
}
